import { createStore, applyMiddleware, combineReducers, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { useRouterHistory } from 'react-router';
import { syncHistoryWithStore, routerReducer, routerMiddleware } from 'react-router-redux';
import { createHashHistory } from 'history';

import webReducer from '../reducers/webReducer';
import businessReducer from '../reducers/businessReducer';

// 所有的reducer放在这个里面
const rootReducer = combineReducers({
  routing: routerReducer,
  webReducer,
  businessReducer,
});

const appHistory = useRouterHistory(createHashHistory)({ queryKey: false });

// 所有的中间件放在这
let createStoreWithMiddleware
if (!(window.__REDUX_DEVTOOLS_EXTENSION__ || window.__REDUX_DEVTOOLS_EXTENSION__)) {
  createStoreWithMiddleware = applyMiddleware(
    thunkMiddleware,
    routerMiddleware(appHistory))(createStore);
} else {
  createStoreWithMiddleware = compose(
    applyMiddleware(
      thunkMiddleware,
      routerMiddleware(appHistory)),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())(createStore);
}

export const store = createStoreWithMiddleware(rootReducer);
export const history = syncHistoryWithStore(appHistory, store);
